% select next generation from all seeds matrix
function result = select_next_generation(all_seeds_matrix)

global seeds;
global func;

next_seeds_matrix = [];
all_seeds_number = size(all_seeds_matrix, 1);
all_seeds_fitness = zeros(1, all_seeds_number);

for seeds_index = 1: all_seeds_number 
     seed_fitness = func(all_seeds_matrix(seeds_index,:));
     all_seeds_fitness(seeds_index) = seed_fitness;
end

% calculate the best seed fitness and find best seed index
best_seed_fitness = min(all_seeds_fitness);
best_seed_index = find(all_seeds_fitness == best_seed_fitness, 1, 'first');

% matlab bug: when adding a column/row into a matrix by manipulating the
% subscription of the matrix will cause error, so change another way.
% ??? Subscripted assignment dimension mismatch
% select best seed
next_seeds_matrix = [next_seeds_matrix; all_seeds_matrix(best_seed_index,:)];

% matlab bug: when you delete a column or row in a matrix, then iterate the
% matrix will cause index out of bounds error at some execution case.
% all_seeds_matrix(best_seed_index,:) = [];

all_seeds_probability = zeros(1, all_seeds_number);

% calculate all seeds distance between each other
[seeds_distance_total, distance_total] = calculate_seeds_distance(all_seeds_matrix);

% randomly select the n - 1 locations for next according to the probability
% generation
for seed_index = 1 : all_seeds_number
%     selected_seed = all_seeds_matrix(seed_index,:);
%     all_seeds_probability(seed_index) = probability(selected_seed, all_seeds_matrix);
    all_seeds_probability(seed_index) = seeds_distance_total(seed_index) / distance_total;
end
all_seeds_cumulate_probability = cumsum(all_seeds_probability, 2);

for index = 1 :seeds - 1
    hitting_index = 1;
    spinning_wheel = rand;
    while spinning_wheel > all_seeds_cumulate_probability(hitting_index) && ...
                                            hitting_index < all_seeds_number
        hitting_index = hitting_index + 1;
    end
    next_seeds_matrix = [next_seeds_matrix; all_seeds_matrix(hitting_index,:)];
end
result = next_seeds_matrix;
end
